var fs = require('fs');

exports.changeglobal = function(req, res, next) {
    var body = req.body;
    var name = body.name;
    var discription = body.discription;
    var logo = body.logo;
    var coverplan = body.coverplan;

    var text = "var global = {name: '" + name + "',discription: '" + discription + "',logo: '" + logo + "',coverplan: '" + coverplan + "'};exports.Global = global;";

    fs.writeFile('../config/genset.js', text, function(err) {
        if (err) throw err;
        console.log('It\'s saved!'); //文件被保存

        res.send({
            status: 0,
            msg: {}
        });
    });
};

exports.upload = function(req, res, next) {
    console.log(req.files['logo']);

    var oldfilePath = '';
    var kind = '';
    var filename = '';
    var newfilePath = '';

    if (req.files['coverplan']) {
        oldfilePath = req.files['coverplan'].path;
        kind = oldfilePath.split(".")[1];
        filename = req.files['coverplan'].name;
        newfilePath = '/../public/img/' + filename + '.' + kind;
    }

    if (req.files['logo']) {
        oldfilePath = req.files['logo'].path;
        kind = oldfilePath.split(".")[1];
        filename = req.files['logo'].name;
        newfilePath = '/../public/img/' + filename + '.' + kind;
    }

    fs.rename(oldfilePath, __dirname + newfilePath, function(err) {
        if (err) {
            res.send({
                error: 'Upload fail!'
            });
            return;
        }

        res.send({
            initialPreviewConfig: [{
                caption: '/img/' + filename + '.' + kind,
                width: '300px',
                url: '', // server delete action 
                key: 100,
                extra: {
                    id: 100
                }
            }]
        });
    });
};